package com.example.web.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

/**
 * 自定义认证授权realm
 * <p>
 * Created by YangGang on 2021/12/14 16:10。
 */
public class CustomRealm extends AuthorizingRealm {

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取身份信息
        Object primaryPrincipal = principalCollection.getPrimaryPrincipal();
        //通过省份获取用户的角色和权限
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRole("admin");
        info.addRole("test");
        info.addRole("master");
        info.addStringPermission("user:create");
        info.addStringPermission("user:update:zs");
        info.addStringPermission("task:update:02");
        info.addStringPermission("task:create");

        return info;
    }

    //身份认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取身份
        Object principal = authenticationToken.getPrincipal();
        //数据库查询身份
        if (principal != null) {
            SimpleAuthenticationInfo simpleAuthenticationInfo =
                    new SimpleAuthenticationInfo(
                            principal,
                            "967812f14cf0ea0269bd119fca68aa27",
                            ByteSource.Util.bytes("&*(^fgefg&YBNY*T"),
                            this.getName());
            return simpleAuthenticationInfo;
        }

        return null;
    }
}
